package com.sansi.bleFloodlight.activity;

import android.bluetooth.BluetoothDevice;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.graphics.ColorUtils;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.a1anwang.okble.client.scan.BLEScanResult;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.example.blelibrary.ble.BleCommand;
import com.gcssloop.color_picker.ColorPicker;
import com.gcssloop.widget.ArcSeekBar;
import com.gcssloop.widget.BubbleSeekBar;

import com.my.httpapi.api.annotation.Layout;
import com.my.httpapi.api.baseUtils.LogUtils;
import com.my.httpapi.api.baseView.BaseActivity;
import com.sansi.bleFloodlight.R;
import com.sansi.bleFloodlight.adapter.LightPresetAdapter;
import com.sansi.bleFloodlight.ble.BleManageUtils;
import com.sansi.bleFloodlight.ble.bleInterface.BleManageListener;
import com.sansi.bleFloodlight.ble.bleInterface.IBleManage;
import com.sansi.bleFloodlight.db.TableDevice;
import com.sansi.bleFloodlight.model.ChangeLightColorEvent;
import com.sansi.bleFloodlight.model.ChangeLightProgressEvent;
import com.sansi.bleFloodlight.model.RemoveLightEvent;
import com.sansi.bleFloodlight.utils.ActivityUtils;
import com.sansi.bleFloodlight.utils.MMKVUtils;
import com.sansi.bleFloodlight.utils.RouterPath;
import com.sansi.bleFloodlight.utils.StringUtils;
import com.sansi.bleFloodlight.view.SpaceHomeLightItemDecoration;
import com.tencent.mmkv.MMKV;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

@Layout(R.layout.layout_activity_light_close)
@Route(path = RouterPath.lightClosePath)
public class LightCloseActivity extends BaseActivity implements BleManageListener {

    private ImageView ivBack, ivLightTurn, ivLightBrightness, ivLightColor, ivLightPreset;
    private View llLightTurn, llLightBrightness, llLightColor, llLightPreset;
    private View viewClose, viewBrightness, viewColor, viewPreset;
    private TextView tvLightTurn, tvLightBrightness, tvLightColor, tvLightPreset, tvColorTemperatureProgress;
    private ColorPicker picker;
    private ArcSeekBar mArcSeekBar;
    private BubbleSeekBar bubbleSeekBar;
    private LinearLayout llLightBg;
    private RecyclerView recyclerView;
    private LightPresetAdapter lightPresetAdapter;
    private ImageView ivColorSwitch, ivSetting, ivClock;

    private int status;//关灯(0-默认 -1-亮度  -2-颜色  -3-场景)  1-亮度  2-颜色 3-场景
    private MMKV mmkv = MMKV.defaultMMKV();
    private int colors[] = {0xff06030B, 0xff06030B};
    private List<String> list = new ArrayList<>();
    private boolean isColor = true;//是否是颜色模式下

    private IBleManage iBleManage;

    public static final int INT_UNIND = 3;
    public static final int SEND_UNBIND = 4;

    private HandlerThread handlerThread;
    private Handler workHandler;
    private int int_write = -1;// 0-写入netkey  1-查询状态

    @Autowired
    public BluetoothDevice device;
    @Autowired
    public int color;
    @Autowired
    public int progress;

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        llLightBg = findViewById(R.id.ll_light_bg);
        ivBack = findViewById(R.id.iv_back);
        ivLightTurn = findViewById(R.id.iv_light_turn);
        ivLightBrightness = findViewById(R.id.iv_light_brightness);
        ivLightColor = findViewById(R.id.iv_light_color);
        ivLightPreset = findViewById(R.id.iv_light_preset);
        llLightTurn = findViewById(R.id.ll_light_turn);
        llLightBrightness = findViewById(R.id.ll_light_brightness);
        llLightColor = findViewById(R.id.ll_light_color);
        llLightPreset = findViewById(R.id.ll_light_preset);
        tvLightTurn = findViewById(R.id.tv_light_turn);
        tvLightBrightness = findViewById(R.id.tv_light_brightness);
        tvLightColor = findViewById(R.id.tv_light_color);
        tvLightPreset = findViewById(R.id.tv_light_preset);
        viewClose = findViewById(R.id.view_close);
        viewBrightness = findViewById(R.id.view_brightness);
        viewColor = findViewById(R.id.view_color);
        viewPreset = findViewById(R.id.view_preset);
        picker = findViewById(R.id.color_picker);
        bubbleSeekBar = findViewById(R.id.bubble_seek_bar);
        recyclerView = findViewById(R.id.recycler_view);
        ivColorSwitch = findViewById(R.id.iv_color_switch);
        mArcSeekBar = findViewById(R.id.arc_seek_bar);
        tvColorTemperatureProgress = findViewById(R.id.tv_color_temperature_progress);
        ivSetting = findViewById(R.id.iv_setting);
        ivClock = findViewById(R.id.iv_clock);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        iBleManage = new BleManageUtils(this, this);
        BLEScanResult bleScanResult = new BLEScanResult(device, new byte[0], 0);
        iBleManage.setBLEScanResult(bleScanResult);
        iBleManage.connect(false);
        status = mmkv.decodeInt(MMKVUtils.STATUS, 0);
        if (color != 0) {
            colors[0] = color;
            colors[1] = ColorUtils.setAlphaComponent(color, 128);
        }
        initList();
        showChoose();
        ivBack.setOnClickListener(view -> finish());
        ivLightTurn.setOnClickListener(view -> {
            if (status == 0 || status == -1) {
                status = 1;
            } else if (status == -2) {
                status = 2;
            } else if (status == -3) {
                status = 3;
            } else if (status == 1) {
                status = -1;
            } else if (status == 2) {
                status = -2;
            } else if (status == 3) {
                status = -3;
            }
            showChoose();
        });
        ivLightBrightness.setOnClickListener(view -> {
            if (status == 1) return;
            status = 1;
            showChoose();
        });
        ivLightColor.setOnClickListener(view -> {
            if (status == 2) return;
            status = 2;
            showChoose();
        });
        ivLightPreset.setOnClickListener(view -> {
            if (status == 3) return;
            status = 3;
            showChoose();
        });

        picker.setColor(colors[0]);
        picker.setColorChangedListener(new ColorPicker.OnColorSelectedListener() {
            @Override
            public void onColorChanged(int color, int[] rgbw, boolean isTouch) {
                colors[0] = color;
                colors[1] = ColorUtils.setAlphaComponent(color, 128);
                GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
                llLightBg.setBackgroundDrawable(gradientDrawable);
            }

            @Override
            public void onColorSelected(int color, int[] rgbw, boolean isTouch) {
                //保存顔色并且更新列表页面
                EventBus.getDefault().post(new ChangeLightColorEvent(device, color));
            }
        });
        mArcSeekBar.setArcColors(R.array.arc_colors_custom);
        mArcSeekBar.setMaxValue(100);
        mArcSeekBar.setMinValue(0);
        tvColorTemperatureProgress.setText(mArcSeekBar.getProgress() + "%");
        mArcSeekBar.setOnProgressChangeListener(new ArcSeekBar.OnProgressChangeListener() {
            @Override
            public void onProgressChanged(ArcSeekBar seekBar, int progress, boolean isUser) {
                tvColorTemperatureProgress.setText(progress + "%");
            }

            @Override
            public void onStartTrackingTouch(ArcSeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(ArcSeekBar seekBar) {

            }
        });

        bubbleSeekBar.setProgress(progress);
        tvLightBrightness.setText(progress + "%");
        bubbleSeekBar.setOnProgressChangeListener(new BubbleSeekBar.OnProgressChangeListener() {
            @Override
            public void onProgressChanged(BubbleSeekBar seekBar, int p, boolean isUser) {
                progress = p;
                tvLightBrightness.setText(progress + "%");
            }

            @Override
            public void onStartTrackingTouch(BubbleSeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(BubbleSeekBar seekBar) {
                //保存亮度
                EventBus.getDefault().post(new ChangeLightProgressEvent(device, progress));
            }
        });

        ivColorSwitch.setOnClickListener(view -> {
            if (isColor) {
                isColor = false;
                ivColorSwitch.setImageResource(R.drawable.btn_change_color);
                picker.setVisibility(View.GONE);
                mArcSeekBar.setVisibility(View.VISIBLE);
                tvColorTemperatureProgress.setVisibility(View.VISIBLE);
            } else {
                isColor = true;
                ivColorSwitch.setImageResource(R.drawable.btn_change_temperature);
                picker.setVisibility(View.VISIBLE);
                mArcSeekBar.setVisibility(View.GONE);
                tvColorTemperatureProgress.setVisibility(View.GONE);
            }
        });

        ivSetting.setOnClickListener(view -> RouterPath.gotoDeviceInfoPath(device));

        ivClock.setOnClickListener(view -> RouterPath.gotoTimePath());

        handlerThread = new HandlerThread("lookDeviceStatus");
        handlerThread.start();
        workHandler = new Handler(handlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case INT_UNIND:
                        int_write = 0;
                        iBleManage.writeData(BleCommand.getNetkeyData(ActivityUtils.getLocalNetKey(), 16));
                        break;
                    case SEND_UNBIND:
                        int_write = 1;
                        List<TableDevice> listDevice = LitePal.findAll(TableDevice.class);
                        for (int i = 0; i < listDevice.size(); i++) {
                            TableDevice tableDevice = listDevice.get(i);
                            if (tableDevice.getMac().equals(device.getAddress())) {
                                byte[] data = BleCommand.getDeviceStateData(ActivityUtils.toBytes(tableDevice.getUnicast_address()), 2);
                                iBleManage.writeData(data);
                                break;
                            }
                        }
                        break;
                }
            }
        };
    }

    @Override
    protected void destory() {
        EventBus.getDefault().unregister(this);
        if (handlerThread != null)
            handlerThread.quit();
    }

    @Override
    protected String showTitle() {
        return null;
    }

    @Override
    protected boolean statusBarIsBlack() {
        return false;
    }

    @Override
    protected boolean showLeftArrow() {
        return false;
    }

    private void initList() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(gridLayoutManager);
        lightPresetAdapter = new LightPresetAdapter();
        recyclerView.setAdapter(lightPresetAdapter);
        int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.dp_11);
        recyclerView.addItemDecoration(new SpaceHomeLightItemDecoration(spacingInPixels));
        createData();
    }

    private void showChoose() {
        mmkv.encode(MMKVUtils.STATUS, status);
        llLightBrightness.setVisibility(View.VISIBLE);
        llLightColor.setVisibility(View.VISIBLE);
        llLightPreset.setVisibility(View.VISIBLE);
        if (status == 0 || status == -1 || status == -2 || status == -3) {
            llLightBg.setBackgroundResource(R.drawable.turnon_bg);
            llLightBrightness.setVisibility(View.GONE);
            llLightColor.setVisibility(View.GONE);
            llLightPreset.setVisibility(View.GONE);
            ivLightTurn.setImageResource(R.drawable.power_on);
            tvLightTurn.setTextColor(getResources().getColor(R.color.color_white_15));
            tvLightBrightness.setTextColor(getResources().getColor(R.color.color_white_50));
            tvLightColor.setTextColor(getResources().getColor(R.color.color_white_50));
            tvLightPreset.setTextColor(getResources().getColor(R.color.color_white_50));
            viewClose.setVisibility(View.VISIBLE);
            viewBrightness.setVisibility(View.GONE);
            viewColor.setVisibility(View.GONE);
            viewPreset.setVisibility(View.GONE);
        } else if (status == 1) {
            GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
            llLightBg.setBackgroundDrawable(gradientDrawable);
            ivLightTurn.setImageResource(R.drawable.power_off);
            ivLightBrightness.setImageResource(R.drawable.brightness_s);
            ivLightColor.setImageResource(R.drawable.color_n);
            ivLightPreset.setImageResource(R.drawable.flowing_n);
            tvLightTurn.setTextColor(getResources().getColor(R.color.color_white_50));
            tvLightBrightness.setTextColor(getResources().getColor(R.color.color_white_15));
            tvLightColor.setTextColor(getResources().getColor(R.color.color_white_50));
            tvLightPreset.setTextColor(getResources().getColor(R.color.color_white_50));
            viewClose.setVisibility(View.GONE);
            viewBrightness.setVisibility(View.VISIBLE);
            viewColor.setVisibility(View.GONE);
            viewPreset.setVisibility(View.GONE);
        } else if (status == 2) {
            GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
            llLightBg.setBackgroundDrawable(gradientDrawable);
            ivLightTurn.setImageResource(R.drawable.power_off);
            ivLightBrightness.setImageResource(R.drawable.brightness_n);
            ivLightColor.setImageResource(R.drawable.color_s);
            ivLightPreset.setImageResource(R.drawable.flowing_n);
            tvLightTurn.setTextColor(getResources().getColor(R.color.color_white_50));
            tvLightBrightness.setTextColor(getResources().getColor(R.color.color_white_50));
            tvLightColor.setTextColor(getResources().getColor(R.color.color_white_15));
            tvLightPreset.setTextColor(getResources().getColor(R.color.color_white_50));
            viewClose.setVisibility(View.GONE);
            viewBrightness.setVisibility(View.GONE);
            viewColor.setVisibility(View.VISIBLE);
            viewPreset.setVisibility(View.GONE);
        } else if (status == 3) {
            llLightBg.setBackgroundResource(R.color.color_bg);
            ivLightTurn.setImageResource(R.drawable.power_off);
            ivLightBrightness.setImageResource(R.drawable.brightness_n);
            ivLightColor.setImageResource(R.drawable.color_n);
            ivLightPreset.setImageResource(R.drawable.flowing_s);
            tvLightTurn.setTextColor(getResources().getColor(R.color.color_white_50));
            tvLightBrightness.setTextColor(getResources().getColor(R.color.color_white_50));
            tvLightColor.setTextColor(getResources().getColor(R.color.color_white_50));
            tvLightPreset.setTextColor(getResources().getColor(R.color.color_white_15));
            viewClose.setVisibility(View.GONE);
            viewBrightness.setVisibility(View.GONE);
            viewColor.setVisibility(View.GONE);
            viewPreset.setVisibility(View.VISIBLE);
        }
    }

    private void createData() {
        for (int i = 0; i < 4; i++) {
            list.add("");
        }
        lightPresetAdapter.setNewData(list);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void removeLightEvent(RemoveLightEvent removeLightEvent) {
        finish();
    }

    @Override
    public void openNotify() {
        message_init_bind();
    }

    @Override
    public void onDisconnected() {

    }

    @Override
    public void onReceivedValue(String uuid, int code,String value) {
        if (int_write == 0 && code==BleManageUtils.SUCESS) {
            message_send_bind();
        } else if (int_write == 1 && code==BleManageUtils.SUCESS) {
            //取出灯状态
            String  status_16=   value.substring(16,20);
            String status_2 = Integer.toBinaryString(StringUtils.hexTo10(status_16));
            LogUtils.e(status_2);
        }
    }

    private void message_init_bind() {
        Message msg = Message.obtain();
        msg.what = INT_UNIND;
        workHandler.sendMessage(msg);
    }

    private void message_send_bind() {
        Message msg = Message.obtain();
        msg.what = SEND_UNBIND;
        workHandler.sendMessage(msg);
    }
}
